package org.jeecg.modules.demo.couponmanagement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.couponmanagement.entity.CouponManagement;
import org.jeecg.modules.demo.couponmanagement.service.ICouponManagementService;
import org.jeecg.modules.demo.vipcardcoupon.entity.VipCardCoupon;
import org.jeecg.modules.demo.vipcardcoupon.service.IVipCardCouponService;
import org.jeecg.modules.util.RedisUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

/**
 * 贵宾卡优惠券管理
 */
@Api(tags = "贵宾卡优惠券管理")
@RestController
@RequestMapping("/couponmanagement/couponManagement")
@Slf4j
public class CouponManagementController extends JeecgController<CouponManagement, ICouponManagementService> {
    @Autowired
    private ICouponManagementService couponManagementService;
    @Autowired
    private IVipCardCouponService vipCardCouponService;
    @Autowired
    private RedisUtils redisUtils;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "贵宾卡优惠券管理-分页列表查询")
    @ApiOperation(value = "贵宾卡优惠券管理-分页列表查询", notes = "贵宾卡优惠券管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CouponManagement couponManagement,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<CouponManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, couponManagement, req.getParameterMap());
        Page<CouponManagement> page = new Page<>(pageNo, pageSize);
        IPage<CouponManagement> pageList = couponManagementService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 不分页列表查询
     */
    @AutoLog(value = "贵宾卡优惠券管理-不分页列表查询")
    @ApiOperation(value = "贵宾卡优惠券管理-不分页列表查询", notes = "贵宾卡优惠券管理-不分页列表查询")
    @GetMapping(value = "/lists")
    public Result<?> queryPageLists(CouponManagement couponManagement,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "1000") Integer pageSize,
                                    HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<CouponManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, couponManagement, req.getParameterMap());
        Page<CouponManagement> page = new Page<>(pageNo, pageSize);
        IPage<CouponManagement> pageList = couponManagementService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     */
    @AutoLog(value = "贵宾卡优惠券管理-添加")
    @ApiOperation(value = "贵宾卡优惠券管理-添加", notes = "贵宾卡优惠券管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CouponManagement couponManagement, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        couponManagement.setStoreId(storeId);
        // 当前店铺全部优惠劵
        List<CouponManagement> list = couponManagementService.list(new QueryWrapper<CouponManagement>().eq("store_id", storeId));
        // list中与couponManagement同名的优惠劵个数
        long count = list.stream().filter(cm -> cm.getTicketName().equals(couponManagement.getTicketName())).count();
        if (count > 0) {
            return Result.error("添加失败，该店铺已有同名优惠劵！");
        }

        String fullSelect = couponManagement.getFullSelect();
        if (!"0".equals(fullSelect) && !"1".equals(fullSelect) && !"2".equals(fullSelect)) {
            return Result.error("添加失败，使用条件类型错误！");
        }
        if ("0".equals(fullSelect)) {
            // x年x月x日-x年x月x日
            if (couponManagement.getFullDate() == null || couponManagement.getFullNextDate() == null) {
                return Result.error("添加失败，时间区间不能为空！");
            }
            couponManagement.setManualDateNum(null);
            couponManagement.setTicketDetail(sdf.format(couponManagement.getFullDate()) + "到" + sdf.format(couponManagement.getFullNextDate()) + "之间");
        }
        if ("1".equals(fullSelect)) {
            // 领取x天以内
            if (StringUtils.isEmpty(couponManagement.getManualDateNum())) {
                return Result.error("添加失败，过期天数不能为空！");
            }
            int num3;
            try {
                num3 = Integer.parseInt(couponManagement.getManualDateNum());
            } catch (Exception e) {
                log.error("发生异常", e);
                return Result.error("添加失败，数据格式不正确！");
            }
            if (num3 <= 0) {
                return Result.error("添加失败，过期天数必须大于0！");
            }
            couponManagement.setFullDate(null);
            couponManagement.setFullNextDate(null);
            couponManagement.setTicketDetail("领取之日起，" + num3 + "天之内有效");
        }
        if ("2".equals(fullSelect)) {
            // 永久有效
            couponManagement.setManualDateNum(null);
            couponManagement.setFullDate(null);
            couponManagement.setFullNextDate(null);
            couponManagement.setTicketDetail("永久有效");
        }

        String ticketType = couponManagement.getTicketType();
        if (!"0".equals(ticketType) && !"1".equals(ticketType) && !"2".equals(ticketType)) {
            return Result.error("添加失败，优惠劵类型错误！");
        }

        // 满x
        double num1;
        try {
            num1 = Double.parseDouble(couponManagement.getFullNum());
        } catch (Exception e) {
            log.error("发生异常", e);
            return Result.error("添加失败，数据格式不正确！");
        }
        if (num1 < 0) {
            return Result.error("添加失败，满减金额不能为负数！");
        }
        if ("0".equals(ticketType)) {
            // 打y折
            if (StringUtils.isEmpty(couponManagement.getFullNextNum())) {
                return Result.error("添加失败，折扣不能为空！");
            }
            double num2;
            try {
                num2 = Double.parseDouble(couponManagement.getFullNextNum());
            } catch (Exception e) {
                log.error("发生异常", e);
                return Result.error("添加失败，数据格式不正确！");
            }
            if (num2 <= 0 || num2 >= 10) {
                return Result.error("添加失败，折扣应介于0-10之间！");
            }
            couponManagement.setIsSelect(null);
            couponManagement.setIsSelectNext(null);
            couponManagement.setServiceConditions("满" + num1 + "元打" + num2 + "折");
        }
        if ("1".equals(ticketType)) {
            // 送y
            if (StringUtils.isEmpty(couponManagement.getFullNextNum())) {
                return Result.error("添加失败，赠送内容不能为空！");
            }
            if (StringUtils.isEmpty(couponManagement.getIsSelect()) || StringUtils.isEmpty(couponManagement.getIsSelectNext())) {
                return Result.error("添加失败，必须选择叠加方式！");
            }
            couponManagement.setServiceConditions("满" + num1 + "元送" + couponManagement.getFullNextNum());
            if ("0".equals(couponManagement.getIsSelectNext())) {
                couponManagement.setTicketDetail(couponManagement.getTicketDetail() + "，此优惠券可叠加使用");
            } else {
                couponManagement.setTicketDetail(couponManagement.getTicketDetail() + "，此优惠券不可叠加使用");
            }
            if ("0".equals(couponManagement.getIsSelect())) {
                couponManagement.setTicketDetail(couponManagement.getTicketDetail() + "，此优惠券可与其他券叠加");
            } else {
                couponManagement.setTicketDetail(couponManagement.getTicketDetail() + "，此优惠券不可与其他券叠加");
            }

        }
        if ("2".equals(ticketType)) {
            // 减y
            if (StringUtils.isEmpty(couponManagement.getFullNextNum())) {
                return Result.error("添加失败，满减额度不能为空！");
            }
            double num2;
            try {
                num2 = Double.parseDouble(couponManagement.getFullNextNum());
            } catch (Exception e) {
                log.error("发生异常", e);
                return Result.error("添加失败，数据格式不正确！");
            }
            if (num1 <= num2) {
                return Result.error("添加失败，满减额度不能大于满减金额！");
            }
            couponManagement.setIsSelect(null);
            couponManagement.setIsSelectNext(null);
            couponManagement.setServiceConditions("满" + num1 + "元减" + num2 + "元");
        }

        couponManagement.setTicketNumber(getNewCode(storeId));
        couponManagementService.save(couponManagement);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     */
    @AutoLog(value = "贵宾卡优惠券管理-编辑")
    @ApiOperation(value = "贵宾卡优惠券管理-编辑", notes = "贵宾卡优惠券管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CouponManagement couponManagement, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 当前店铺全部优惠劵
        List<CouponManagement> list = couponManagementService.list(new QueryWrapper<CouponManagement>()
                .eq("store_id", storeId)
                .ne("id", couponManagement.getId()));
        // list中与couponManagement同名的优惠劵个数
        long count = list.stream().filter(cm -> cm.getTicketName().equals(couponManagement.getTicketName())).count();
        if (count > 0) {
            return Result.error("编辑失败，该店铺已有同名优惠劵！");
        }

        String fullSelect = couponManagement.getFullSelect();
        if (!"0".equals(fullSelect) && !"1".equals(fullSelect) && !"2".equals(fullSelect)) {
            return Result.error("编辑失败，使用条件类型错误！");
        }
        if ("0".equals(fullSelect)) {
            // x年x月x日-x年x月x日
            if (couponManagement.getFullDate() == null || couponManagement.getFullNextDate() == null) {
                return Result.error("编辑失败，时间区间不能为空！");
            }
            couponManagement.setManualDateNum(null);
            couponManagement.setTicketDetail(sdf.format(couponManagement.getFullDate()) + "到" + sdf.format(couponManagement.getFullNextDate()) + "之间");
        }
        if ("1".equals(fullSelect)) {
            // 领取x天以内
            if (StringUtils.isEmpty(couponManagement.getManualDateNum())) {
                return Result.error("编辑失败，过期天数不能为空！");
            }
            int num3;
            try {
                num3 = Integer.parseInt(couponManagement.getManualDateNum());
            } catch (Exception e) {
                log.error("发生异常", e);
                return Result.error("编辑失败，数据格式不正确！");
            }
            if (num3 <= 0) {
                return Result.error("编辑失败，过期天数必须大于0！");
            }
            couponManagement.setFullDate(null);
            couponManagement.setFullNextDate(null);
            couponManagement.setTicketDetail("领取之日起，" + num3 + "天之内有效");
        }
        if ("2".equals(fullSelect)) {
            // 永久有效
            couponManagement.setManualDateNum(null);
            couponManagement.setFullDate(null);
            couponManagement.setFullNextDate(null);
            couponManagement.setTicketDetail("永久有效");
        }

        String ticketType = couponManagement.getTicketType();
        if (!"0".equals(ticketType) && !"1".equals(ticketType) && !"2".equals(ticketType)) {
            return Result.error("编辑失败，优惠劵类型错误！");
        }

        // 满x
        double num1;
        try {
            num1 = Double.parseDouble(couponManagement.getFullNum());
        } catch (Exception e) {
            log.error("发生异常", e);
            return Result.error("编辑失败，数据格式不正确！");
        }
        if (num1 < 0) {
            return Result.error("编辑失败，满减金额不能为负数！");
        }
        if ("0".equals(ticketType)) {
            // 打y折
            if (StringUtils.isEmpty(couponManagement.getFullNextNum())) {
                return Result.error("编辑失败，折扣不能为空！");
            }
            double num2;
            try {
                num2 = Double.parseDouble(couponManagement.getFullNextNum());
            } catch (Exception e) {
                log.error("发生异常", e);
                return Result.error("编辑失败，数据格式不正确！");
            }
            if (num2 <= 0 || num2 >= 10) {
                return Result.error("编辑失败，折扣应介于0-10之间！");
            }
            couponManagement.setIsSelect(null);
            couponManagement.setIsSelectNext(null);
            couponManagement.setServiceConditions("满" + num1 + "元打" + num2 + "折");
        }
        if ("1".equals(ticketType)) {
            // 送y
            if (StringUtils.isEmpty(couponManagement.getFullNextNum())) {
                return Result.error("编辑失败，赠送内容不能为空！");
            }
            if (StringUtils.isEmpty(couponManagement.getIsSelect()) || StringUtils.isEmpty(couponManagement.getIsSelectNext())) {
                return Result.error("编辑失败，必须选择叠加方式！");
            }
            couponManagement.setServiceConditions("满" + num1 + "元送" + couponManagement.getFullNextNum());
            if ("0".equals(couponManagement.getIsSelectNext())) {
                couponManagement.setTicketDetail(couponManagement.getTicketDetail() + "，此优惠券可叠加使用");
            } else {
                couponManagement.setTicketDetail(couponManagement.getTicketDetail() + "，此优惠券不可叠加使用");
            }
            if ("0".equals(couponManagement.getIsSelect())) {
                couponManagement.setTicketDetail(couponManagement.getTicketDetail() + "，此优惠券可与其他券叠加");
            } else {
                couponManagement.setTicketDetail(couponManagement.getTicketDetail() + "，此优惠券不可与其他券叠加");
            }

        }
        if ("2".equals(ticketType)) {
            // 减y
            if (StringUtils.isEmpty(couponManagement.getFullNextNum())) {
                return Result.error("编辑失败，满减额度不能为空！");
            }
            double num2;
            try {
                num2 = Double.parseDouble(couponManagement.getFullNextNum());
            } catch (Exception e) {
                log.error("发生异常", e);
                return Result.error("编辑失败，数据格式不正确！");
            }
            if (num1 <= num2) {
                return Result.error("编辑失败，满减额度不能大于满减金额！");
            }
            couponManagement.setIsSelect(null);
            couponManagement.setIsSelectNext(null);
            couponManagement.setServiceConditions("满" + num1 + "元减" + num2 + "元");
        }
        couponManagementService.updateById(couponManagement);
        couponManagementService.updateSetNull(couponManagement);
        return Result.OK("编辑成功！");
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "贵宾卡优惠券管理-通过id删除")
    @ApiOperation(value = "贵宾卡优惠券管理-通过id删除", notes = "贵宾卡优惠券管理-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> delete(@RequestParam("id") String id) {
        couponManagementService.removeById(id);
        vipCardCouponService.remove(new QueryWrapper<VipCardCoupon>().eq("coupon_id", id));
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "贵宾卡优惠券管理-批量删除")
    @ApiOperation(value = "贵宾卡优惠券管理-批量删除", notes = "贵宾卡优惠券管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(@RequestParam("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        couponManagementService.removeByIds(idList);
        vipCardCouponService.remove(new QueryWrapper<VipCardCoupon>().in("coupon_id", idList));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "贵宾卡优惠券管理-通过id查询")
    @ApiOperation(value = "贵宾卡优惠券管理-通过id查询", notes = "贵宾卡优惠券管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CouponManagement couponManagement = couponManagementService.getById(id);
        if (couponManagement == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(couponManagement);
    }

    //获取优惠劵编码
    @AutoLog(value = "贵宾卡优惠券管理-获取优惠劵编码")
    @ApiOperation(value = "贵宾卡优惠券管理-获取优惠劵编码", notes = "贵宾卡优惠券管理-获取优惠劵编码")
    @GetMapping(value = "/getTicketId")
    public Result<?> getTicketId(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        return Result.OK(getNewCode(storeId));
    }

    private int getNewCode(String storeId) {
        QueryWrapper<CouponManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.orderByDesc("ticket_number").last("limit 1");
        CouponManagement bean = couponManagementService.getOne(queryWrapper);
        if (bean == null || bean.getTicketNumber() == null) {
            return 1;
        }
        return bean.getTicketNumber() + 1;
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CouponManagement couponManagement) {
        //return super.exportXls(request, couponManagement, CouponManagement.class, "贵宾卡优惠券管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<CouponManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, couponManagement, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<CouponManagement> pageList = couponManagementService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "贵宾卡优惠券管理"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, CouponManagement.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("贵宾卡优惠券管理数据", "导出人:" + user.getRealname(), "贵宾卡优惠券管理");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CouponManagement.class);
    }

}
